//
//  RequestManger.m
//  Leisure
//
//  Created by 王金晶 on 16/3/11.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "RequestManger.h"

@implementation RequestManger
+ (void)requestWithURL:(NSString *)URLString requestType:(NSString *)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error
{
    RequestManger *request = [[RequestManger alloc]init];
    [request requestWithURL:URLString requestType:requestType parDic:parDic finish:finish error:error];
}
- (void)requestWithURL:(NSString *)URLString requestType:(NSString *)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error
{
    self.finish = finish;
    self.error = error;
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
    if ([requestType isEqualToString:@"RequestPOST"])
    {
        [request setHTTPMethod:@"POST"];
        if (parDic.count != 0) {
            [request setHTTPBody:[self dicToDataWithDic:parDic]];
        }
        
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
           // self.error(error);
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.finish(data);
            });
        }
        
    }];
    //开始请求
    [task resume];
    
}
    //将字典里的键值对 按照key=value 拼接成字符串,最后用&符号连接所有拼接好的字符串
- (NSData *)dicToDataWithDic:(NSDictionary *)dic
{   NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dic) {
        NSString *string = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:string];
    }
    NSString *dataString = [array componentsJoinedByString:@"&"];
    NSLog(@"%@",dataString);
    return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
@end
